<template>
  <a-card title="全部线索">
    <div class="HeadrSearch">
      <!-- 头部搜索框 -->
      <a-input-group compact>
        <a-select v-model:value="SearchType">
          <a-select-option value="线索名称">线索名称</a-select-option>
          <a-select-option value="手机号码">手机号码</a-select-option>
        </a-select>
        <a-input-search style="width: 20%" v-model:value="SearchContent" @search="onSearch">
          <template #enterButton>
            <a-button><template #icon>
                <SearchOutlined />
              </template></a-button>
          </template>
        </a-input-search>
      </a-input-group>
      <a-button type="primary" style="border-radius: 5px" @click="CreateWhole()">新增线索</a-button>
    </div>
    <div class="TableCentent">
      <a-table class="Tables" ref="tableRef" :columns="columns" rowKey="_id" :data-source="data" :pagination="
        {
          pageSize: 5,
          showTotal: (total: any) => `总共 ${total} 项`,
          pageSizeOptions: ['1', '3', '5', '10'],
          showSizeChanger: true,
          showQuickJumper: true,
        }
      " :scroll="{ x: 1500 }" :row-selection="{ fixed: 'left', onChange }"
        :transformCellText="({ text }: any) => (text === 0 ? 0 : text || '-')"
        :rowClassName="(record: any, index: any) => (index % 2 === 1 ? 'table-striped' : null)" bordered>
        <template #TurnoverTime="{ text }">
          {{ formatTime(text.TurnoverTime) }}
        </template>
        <template #PlaceArea="{ text }">
          {{ text.PlaceArea.length === 0 ? '-' : text.PlaceArea.map((item: any) => item.name).join('') }}
        </template>
        <template #FollowUp="{ text }">
          {{ text.cluehistory.length }}
        </template>
        <template #operation="{ record }">
          <a @click="Examine(record)">查看</a>
          <a style="margin-left: 10px;" @click="release(record._id)">释放</a>
          <a style="margin-left: 10px;" @click="Examine(record)">跟进</a>
        </template>
      </a-table>
      <div class="pos" :style="data.length === 0 ? 'bottom:0;position:relative;margin-top:15px;' : ''">
        <!-- <a-button type="primary">全选 / 反选</a-button> -->
        <a-button type="primary" :disabled="selectRows.length === 0" @click="toExcel">导出</a-button>
        <!-- <a-pagination style="align-self: center; position: absolute; right: 20px" size="small" :total="total"
          show-size-changer show-quick-jumper :show-total="(total: any) => `总共
          ${total} 项`" :pageSizeOptions="['1', '3', '5', '10']" v-model:pageSize="pageSize"
          v-model:current="current" /> -->
      </div>
    </div>
    <a-drawer width="1000" placement="right" :closable="false" v-model:visible="visible">
      <div class="drawerHeater">
        <div class="drawerHeater-centent">
          <div class="drawerHeater-ThreadName">
            {{ TableOneData.ThreadName }}
          </div>
          <div class="drawerHeater-ID">
            （
            <span>线索ID： {{ TableOneData._id }}； </span>
            <span style="color: #0078ff; cursor: pointer">转化为客户</span>
            ）
          </div>
          <div class="drawerHeater-p" style="margin-left: 30px">
            转为客户将自动注册企业会员
          </div>
        </div>
        <div class="details">
          <a-row>
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">所属销售：</span><span>{{
                TableOneData.TheirMarketName || '-'
            }}</span>
            </a-col>
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">跟进记录：</span><span>{{
                TableOneData.cluehistory.length
            }}</span>
            </a-col>
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">最后跟进：</span><span>{{
                formatTime(TableOneData.TurnoverTime)
            }}</span>
            </a-col>
          </a-row>
          <a-row style="margin-top: 6px">
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">所在地区：</span><span>{{
                TableOneData.PlaceArea.length === 0 ? '-' : TableOneData.PlaceArea.map((item: any) =>
                  item.name).join('')
            }}</span>
            </a-col>
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">创建人：</span><span>{{
                TableOneData.creatorName
            }}</span>
            </a-col>
            <a-col :span="8"><span style="color: #777; font-size: 14px; font-weight: 400">创建时间：</span><span>{{
                formatTime(TableOneData.createTime)
            }}</span>
            </a-col>
          </a-row>
        </div>
      </div>
      <div class="drawerTab">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="跟进记录">
            <a-row>
              <a-col :span="12">
                <a-form ref="formRef1" :model="formTable" :labelCol="{ span: 4, offset: 0 }"
                  :wrapperCol="{ span: 18, offset: 1 }" :rules="{
                    type: [{
                      required: true, message: '请选择跟进方式'
                    }],
                    result: [{
                      required: true, message: '请输入跟进结果'
                    }]
                  }">
                  <a-form-item label="跟进方式" name="type">
                    <a-select placeholder="请选择" v-model:value="formTable.type">
                      <a-select-option value="当面拜访">当面拜访</a-select-option>
                      <a-select-option value="电话拜访">电话拜访</a-select-option>
                      <a-select-option value="网络拜访">网络拜访</a-select-option>
                      <a-select-option value="其他拜访">其他拜访</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item ref="name" label="联系人" name="contacts">
                    <a-select placeholder="请选择"
                      :value="[TableOneData.Linkman || '-', TableOneData.phone || '-'].join(' | ')">
                      <a-select-option :value="[TableOneData.Linkman || '-', TableOneData.phone || '-'].join(' | ')">{{
                          [TableOneData.Linkman || '-', TableOneData.phone || '-'].join(' | ')
                      }}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item ref="name" label="下次跟进时间" name="name">
                    <a-date-picker v-model:value="formTable.NextFollowupTime" show-time type="date" placeholder="选择日期时间"
                      style="width: 100%" />
                  </a-form-item>
                  <a-form-item label="跟进结果" name="result">
                    <a-textarea :rows="6" v-model:value="formTable.result" />
                  </a-form-item>
                  <a-form-item label="添加图片" name="desc">
                    <a-upload-dragger :file-list="fileList" name="file" :multiple="true" action="/api/index/uploads"
                      @change="handleChange">
                      <p class="ant-upload-drag-icon">
                        <UploadOutlined twoToneColor="#c0c4cc" />
                      </p>
                      <p style="font-size: 14px">
                        将图片拖到此处，或<span style="color: #409eff">点击上传</span>
                      </p>
                      <p style="font-size: 14px">图片上传仅支持jpg/png格式</p>
                    </a-upload-dragger>
                  </a-form-item>
                  <a-form-item :wrapper-col="{ span: 14, offset: 5 }">
                    <a-button type="primary" @click="onFollow">保存跟进记录</a-button>
                  </a-form-item>
                </a-form>
              </a-col>
              <a-col style="border-left: 1px solid #ebeef5;" :span="12">
                <div style="
                    width: 100%;
                    padding: 10px;
                    padding-top: 0;
                    font-size: 14px;
                    font-weight: 600;
                    border-bottom: 1px solid #ebeef5;
                  ">
                  历史跟进<span style="
                      position: absolute;
                      right: 0;
                      font-weight: 400;
                      color: #666666;
                    ">共有 <span style="color: #6ea7d9"> {{ TableOneData.cluehistory.length }}条 </span> 跟进</span>
                </div>
                <div>
                  <a-list item-layout="horizontal" :data-source="TableOneData.cluehistory">
                    <template #renderItem="{ item }">
                      <a-list-item>
                        <a-list-item-meta>
                          <template #title>
                            <div class="followtitle">
                              <div>
                                <span>{{ item.salename }}</span>
                                {{ item.type }}
                                <span>{{ item.contacts }}</span>
                              </div>
                              <div>
                                <span>{{ formatTime(item.createTime) }}</span>
                              </div>
                            </div>
                          </template>
                          <template #avatar>
                            <a-avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                          </template>
                          <template #description>
                            <div class="followinfo">
                              <div style="margin-bottom: 10px;">
                                {{ item.result }}
                              </div>
                              <div>
                                <a-space>
                                  <a-image :width="150" :height="130" :src="'/api' + item1"
                                    v-for="(item1, index) in item.image" />
                                </a-space>
                              </div>
                            </div>
                          </template>
                        </a-list-item-meta>
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="2" tab="线索详情" force-render>
            <a-row>
              <a-col :span="12">
                <a-form ref="formRef" :model="editForm"
                  :rules="{ ThreadName: [{ required: true, message: '线索名称是必填项' }] }" :labelCol="{ span: 4, offset: 0 }"
                  :wrapperCol="{ span: 18, offset: 1 }">
                  <a-form-item ref="ThreadName" label="线索名称" name="ThreadName">
                    <a-input v-model:value="editForm.ThreadName" />
                  </a-form-item>
                  <a-form-item ref="Linkman" label="联系人" name="Linkman">
                    <a-input v-model:value="editForm.Linkman" />
                  </a-form-item>
                  <a-form-item ref="phone" label="联系手机" name="phone">
                    <a-input v-model:value="editForm.phone" />
                  </a-form-item>
                  <a-form-item ref="RelationWeChat" label="联系微信" name="RelationWeChat">
                    <a-input v-model:value="editForm.RelationWeChat" />
                  </a-form-item>
                  <a-form-item label="公司规格" name="CompanySpecification">
                    <a-select v-model:value="editForm.CompanySpecification">
                      <a-select-option value="20人以下">20人以下</a-select-option>
                      <a-select-option value="20-99人">20-99人</a-select-option>
                      <a-select-option value="100-499人">100-499人</a-select-option>
                      <a-select-option value="500-999人">500-999人</a-select-option>
                      <a-select-option value="1000-9999人">1000-9999人</a-select-option>
                      <a-select-option value="10000人以上">10000人以上</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="所属行业" name="Customer">
                    <a-select v-model:value="editForm.Customer">
                      <a-select-option value="计算机软件/硬件">计算机软件/硬件</a-select-option>
                      <a-select-option value="计算机系统/维修">计算机系统/维修</a-select-option>
                      <a-select-option value="通信(设备/运营/服务)">通信(设备/运营/服务)</a-select-option>
                      <a-select-option value="互联网/电子商务">互联网/电子商务</a-select-option>
                      <a-select-option value="网络游戏">网络游戏</a-select-option>
                      <a-select-option value="电子/半导体/集成电路">电子/半导体/集成电路</a-select-option>
                      <a-select-option value="仪器仪表/工业自动化">仪器仪表/工业自动化</a-select-option>
                      <a-select-option value="会计/审计">会计/审计</a-select-option>
                      <a-select-option value="金融(投资/证券)">金融(投资/证券)</a-select-option>
                      <a-select-option value="金融(银行/保险)">金融(银行/保险)</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="所在地区" name="PlaceArea">
                    <al-cascader placeholder="请选择所在地区" :value="editForm.PlaceArea"
                      @input="(e: any) => editForm.PlaceArea = e" level="3" data-type="all" />
                  </a-form-item>
                  <a-form-item ref="Datailed" label="详细地址" name="Datailed">
                    <a-input v-model:value="editForm.Detailed" />
                  </a-form-item>
                  <a-form-item label="备注" name="Remark">
                    <a-textarea :rows="4" v-model:value="editForm.Remark" />
                  </a-form-item>
                  <a-form-item :wrapper-col="{ span: 14, offset: 5 }">
                    <a-button style="width: 110px" type="primary" @click="onSubmit">保存</a-button>
                    <a-button style="margin-left: 15px; width: 110px" type="primary" @click="onSubmit">转化为客户</a-button>
                  </a-form-item>
                </a-form>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-drawer>
  </a-card>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, createVNode } from "vue";
import { QuestionCircleOutlined, SearchOutlined, UploadOutlined } from "@ant-design/icons-vue";
import AlCascader from "@/components/AlCascader/al-cascader.vue";
import { useRouter } from "vue-router";
import { message, Modal } from "ant-design-vue";
import request from "@/request";
import { exportExcel } from '@/utils/exportExcel'
const SearchType = ref("线索名称");
const SearchContent = ref("");
const total = ref(0);
const activeKey = ref("1");
const columns = ref([
  { title: "线索ID", dataIndex: "_id", width: 240 },
  { title: "线索名称", dataIndex: "ThreadName", width: 150 },
  { title: "所属销售", dataIndex: "TheirMarketName", width: 150 },
  { title: "联系人", dataIndex: "Linkman", width: 150, default: '-' },
  { title: "联系电话", dataIndex: "phone", width: 150 },
  { title: "联系微信", dataIndex: "RelationWeChat", width: 150 },
  { title: "客户行业", dataIndex: "Customer", width: 150 },
  { title: "所在地区", slots: { customRender: "PlaceArea" }, width: 200 },
  { title: "详细地址", dataIndex: "Detailed", width: 150 },
  { title: "更新时间", slots: { customRender: "TurnoverTime" }, width: 150 },
  { title: "跟进(次)", slots: { customRender: "FollowUp" }, width: 150 },
  { title: "创建人", dataIndex: "creatorName", width: 150 },
  { title: "备注", dataIndex: "Remark", width: 150 },
  {
    title: "操作",
    fixed: "right",
    width: 140,
    slots: { customRender: "operation" },
  },
]);
interface DataItem {
  key: number;
  id: number;
  ThreadName: string;
  TheirMarket: string;
  Linkman: string;
  phone: number;
  RelationWeChat: string;
  Customer: string;
  PlaceArea: string;
  Detailed: string;
  TurnoverTime: string;
  FollowUp: string;
  Creator: string;
  CompanySpecification: string;
  Remark: string;
  children?: DataItem[];
}
const data: any = ref([]);
// 获取数据的方法
const getData = async () => {
  const { data: res } = await request.get('clue')
  res.data.sort((a: any, b: any) => ((new Date(b.TurnoverTime) as any) - (new Date(a.TurnoverTime) as any)))
  let TheirMarket = JSON.parse((localStorage.getItem('_id') as any))
  res.data = res.data.filter((item: any) => item.TheirMarket == TheirMarket)
  if (SearchType.value === '线索名称') {
    data.value = res.data.filter((item: any) => item.ThreadName.includes(SearchContent.value))
  }
  if (SearchType.value === '手机号码') {
    data.value = res.data.filter((item: any) => item.phone?.includes(SearchContent.value))
  }
}
onMounted(() => {
  getData()
})
// 格式化时间
const formatTime = (timestamp: any) => {
  let date = new Date(timestamp)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
}
const router = useRouter();
const visible = ref<boolean>(false);
const TableOneData: any = ref({});
const formTable = ref({
  type: undefined,
  NextFollowupTime: undefined,
  result: undefined
});

const CreateWhole = () => {
  router.push("/user/compony/wholeAdd");
};
const fileList = ref([])
const handleChange = (info: any) => {
  const status = info.file.status;
  fileList.value = info.fileList
  if (status === "done") {
  } else if (status === "error") {
    message.error(`${info.file.name} 上传失败!`);
  }
};
const formRef1 = ref()
// 保存跟进记录
const onFollow = async () => {
  formRef1.value.validate().then(() => {
    let data = {
      clue: TableOneData.value._id,
      sale: JSON.parse((localStorage.getItem('_id') as any)),
      contacts: TableOneData.value.Linkman,
      type: formTable.value.type,
      result: formTable.value.result,
      image: fileList.value.map((item: any) => item.response.url),
    }
    fileList.value = []
    request.post('clueHistory', data).then(({ data: res }) => {
      if (res.code !== 200) {
        return message.error('跟进失败!')
      }
      message.success('跟进成功!')
      getData()
      visible.value = false
    })
  }).catch(() => { })
}
const editForm: any = ref({})
const Examine = (item: any) => {
  visible.value = true;
  activeKey.value = '1'
  TableOneData.value = JSON.parse(JSON.stringify(item));
  editForm.value = JSON.parse(JSON.stringify(item));
  editForm.value.PlaceArea = editForm.value.PlaceArea || []
};
const formRef = ref()
const onSubmit = () => {
  formRef.value.validate().then((e: any) => {
    request.put('clue', editForm.value).then(({ data }: any) => {
      message.success('保存成功!')
      getData()
      visible.value = false
    })
  }).catch(() => { })
};
const onSearch = () => {
  getData()
};

onMounted(() => {
  total.value = data.length;
});
const selectRows = ref([])
const onChange = (_: any, rows: any) => {
  selectRows.value = rows
}
const toExcel = () => {
  let data = selectRows.value.map((item: any) => {
    return {
      id: item._id || '-',
      tname: item.ThreadName || '-',
      market: item.TheirMarketName || '-',
      link: item.Linkman || '-',
      phone: item.phone || '-',
      wechat: item.RelationWeChat || '-',
      customer: item.Customer || '-',
      place: item.PlaceArea.map((item: any) => item.name).join('') || '-',
      detail: item.Detailed || '-',
      update: formatTime(item.TurnoverTime),
      create: formatTime(item.createTime),
      follow: item.cluehistory.length,
      creator: item.creatorName || '-',
      remark: item.Remark || '-'
    }
  })
  const titleObj = {
    '线索ID': 'id',
    '线索名称': 'tname',
    '所属销售': 'market',
    '联系人': 'link',
    '联系电话': 'phone',
    '联系微信': 'wechat',
    '客户行业': 'customer',
    '所在地区': 'place',
    '详细地址': 'detail',
    '更新时间': 'update',
    '创建时间': 'create',
    '跟进次数': 'follow',
    '创建人': 'creator',
    '备注': 'remark'
  }
  Modal.confirm({
    title: '是否要导出选中的数据?',
    icon: createVNode(QuestionCircleOutlined),
    maskClosable: true,
    centered: true,
    onOk() {
      exportExcel(data, '企业线索', titleObj, "线索数据");
    }
  })
}

const release = (_id: String) => {
  Modal.confirm({
    title: '您确定释放该线索?',
    icon: createVNode(QuestionCircleOutlined),
    maskClosable: true,
    centered: true,
    onOk() {
      request.put('clue', { _id, TheirMarket: null }).then(() => {
        message.success('释放成功!')
        let idx = selectRows.value.findIndex((item: any) => item._id == _id)
        if (idx > -1) {
          selectRows.value.splice(idx, 1)
        }
        getData()
      })
    }
  })
}
</script>

<style lang="scss">
// 头部搜索模块
.HeadrSearch {
  width: 100%;
  display: flex;

  .ant-select-single:not(.ant-select-customize-input) .ant-select-selector {
    height: 45px;
  }

  .ant-select-single .ant-select-selector .ant-select-selection-item,
  .ant-select-single .ant-select-selector .ant-select-selection-placeholder {
    line-height: 43px;
  }

  .ant-input {
    height: 45px;
  }

  .ant-btn-icon-only {
    width: 55px;
    height: 45px;
    background: #f5f7fa;
    border-color: #dcdfe6;
  }

  .ant-btn-icon-only:hover {
    width: 55px;
    height: 45px;
    background: #f5f7fa;
    border-color: #dcdfe6;
  }
}

.pos {
  position: absolute;
  bottom: 35px;
}

.TableCentent {
  width: 100%;
  margin-top: 30px;
}

.drawerHeater {
  width: 100%;
  height: 136px;

  .drawerHeater-centent {
    width: 100%;
    height: 43px;
    display: flex;

    .drawerHeater-ThreadName {
      font-size: 20px;
      height: 20px;
      color: #303033;
      font-weight: 600;
      margin-right: 10px;
    }

    .drawerHeater-ID {
      padding-top: 6px;
      font-size: 14px;
      font-weight: 400;
      color: #777;
    }

    .drawerHeater-p {
      padding-top: 6px;
      font-size: 12px;
      line-height: 21px;
      font-weight: 400;
      color: #c5c0c0;
    }
  }

  .details {
    width: 100%;
  }

  .drawerTab {
    width: 100%;
    height: 50px;
    background-color: #c5c0c0 !important;
  }
}

.followinfo {
  box-sizing: border-box;
  width: 100%;
  padding: 15px;
  background-color: #f7f7f7;
  color: #333;

  .ant-image-img {
    width: 100%;
    height: 100%;
  }
}

.followtitle {
  display: flex;
  justify-content: space-between;

  div:first-of-type span {
    color: #6e86b1;
    font-weight: 600;
  }

  div:last-of-type span {
    color: #999;
  }

}

.ant-list-item {
  padding: 12px;
}
</style>